package reflection;

import java.lang.reflect.Field;

// 什么是反射 ？
public class Test1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        // 通过反射获取类的class对象
        Class<?> c1 = Class.forName("reflection.User");
        System.out.println(c1);  //class reflection.User

        // 一个类在内存中只有一个class对象
        // 一个类被加载后，类的整个结构都会被封装在class对象中
        // 反射可以访问 private 修饰的属性
        Class<?> c2 = Class.forName("reflection.User");
        Class<?> c3 = Class.forName("reflection.User");
        Class<?> c4 = Class.forName("reflection.User");
        System.out.println(c2.hashCode());  //460141958  有相同的hashcode
        System.out.println(c3.hashCode());  //460141958
        System.out.println(c4.hashCode());  //460141958
        System.out.println("=======================");

        //获取类的Class模板
        // 1. 一直具体的类，通过类的class属性获取，可靠，性能高
        Class<User> userClazz1 = User.class;
        System.out.println(userClazz1);  //class reflection.User
        System.out.println(userClazz1.hashCode());  //460141958
        // 2. 已值类的实例，通过市里的getClass()获取Class对象
        User userClazz2 = new User("小宋",19);
        System.out.println(userClazz2.getClass()); //class reflection.User
        System.out.println(userClazz2.hashCode());  //460141958
        // 3. 已知类的全类名（路径.类名），通过Class类的静态方法forName()获取
        Class<?> userClazz3 = Class.forName("reflection.User");
        System.out.println(userClazz3); //class reflection.User
        System.out.println(userClazz3.hashCode());  //460141958
        // 4. 通过ClassLoader获取
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        Class<?> loadClass = classLoader.loadClass("reflection.User");
        System.out.println(loadClass);  //class reflection.User
        System.out.println(loadClass.hashCode());   //460141958
        // 5. 基本内置类的包装类都有一个Type属性
        Class class5 = Integer.TYPE;
        System.out.println(class5); //int
        System.out.println(class5.hashCode());  //1956725890

    }
}

// 实体类pojo,entity
class User{
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
